package com.zlzxm.studentscreen.util.deviceinfo;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

/**
 * CREATE BY zlzxm ON 12/10/20
 */
public class DeviceInfoUtil {

    public static class WifiInfoEntity {

        private String ip;

        private String maskAddress;

        public WifiInfoEntity(String ip, String maskAddress) {
            this.ip = ip;
            this.maskAddress = maskAddress;
        }


        public String getIp() {
            return ip;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }


        public String getMaskAddress() {
            return maskAddress;
        }

        public void setMaskAddress(String maskAddress) {
            this.maskAddress = maskAddress;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            WifiInfoEntity that = (WifiInfoEntity) o;
            return ip.equals(that.ip) &&
                    maskAddress.equals(that.maskAddress);
        }

        @Override
        public int hashCode() {
            return Arrays.hashCode(new String[]{ip, maskAddress});
        }

        @Override
        public String toString() {
            return "WifiInfoEntity{" +
                    "ip='" + ip + '\'' +
                    ", maskAddress='" + maskAddress + '\'' +
                    '}';
        }
    }

    public static final int NO_NET = -1;

    public static final int NET_MOBILE = 1;

    public static final int NET_WIFI = 2;

    private static final String TAG = "DeviceInfoUtil";


    public static boolean isWifiConnected(Context context) {

        ConnectivityManager conMann = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo wifiNetworkInfo = conMann.getActiveNetworkInfo();


        if (wifiNetworkInfo == null) {

            return false;

        }
        int status = -1;

        switch (wifiNetworkInfo.getType()) {

            case ConnectivityManager.TYPE_MOBILE:

                status = NET_MOBILE;

                break;

            case ConnectivityManager.TYPE_WIFI:

                status = NET_WIFI;

                break;

            default:

                break;

        }

        return status == NET_WIFI;

    }


    public static String getSSID(Context context) {

        if (isWifiConnected(context)) {

            ConnectivityManager conMann = (ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (wifiNetworkInfo != null && wifiNetworkInfo.isConnected()) {

                WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

                WifiInfo wifiInfo = wifiManager.getConnectionInfo();

                return wifiInfo.getSSID();
            }

        }

        return null;
    }

    public static String getWifiMac2(Context context) {


        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return wifiInfo.getMacAddress();
        }
        return null;
    }


    public static String getWifiMac(Context context){

        if(isWifiConnected(context))
        {


            try {
                //获取本机器所有的网络接口
                Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
                while (enumeration.hasMoreElements()) {
                    NetworkInterface networkInterface = (NetworkInterface)enumeration.nextElement();
                    //获取硬件地址，一般是MAC
                    byte[] arrayOfByte = networkInterface.getHardwareAddress();
                    String mac = convertMacAddress(arrayOfByte);
                    Log.e(TAG,"mac ：    " + mac );
                    if (arrayOfByte == null || arrayOfByte.length == 0) {
                        continue;
                    }

                    StringBuilder stringBuilder = new StringBuilder();
                    for (byte b : arrayOfByte) {
                        //格式化为：两位十六进制加冒号的格式，若是不足两位，补0
                        stringBuilder.append(String.format("%02X:", b));
                    }
                    if (stringBuilder.length() > 0) {
                        //删除后面多余的冒号
                        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                    }
                    String str = stringBuilder.toString();
                    // wlan0:无线网卡 eth0：以太网卡
                    if (networkInterface.getName().equals("wlan0")) {
                        return str;
                    }
                }
            } catch (SocketException socketException) {
                return null;
            }

        }
        return null;

    }

    public static String getGateWay(Context context) {

        if(isWifiConnected(context)) {

            ConnectivityManager conMann = (ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (wifiNetworkInfo != null && wifiNetworkInfo.isConnected()) {

                WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

                DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();

                return long2ip(dhcpInfo.gateway);
            }

        }

        return null;
    }


    private static String long2ip(long ip) {
        int[] b = new int[4];
        b[0] = (int) ((ip>>24)&0xff);
        b[1] = (int) ((ip>>16)&0xff);
        b[2] = (int) ((ip>>8)&0xff);
        b[3] = (int) (ip&0xff);
        String x;
        x = b[3] +"."+ b[2] +"."+ b[1] +"."+ b[0];
        return x;
    }

    private static String convertMacAddress(byte[] macAddress) {

        String strMacAddress = null;

        if(macAddress == null){

            return null;
        }

        try {

            StringBuilder buffer = new StringBuilder();

            for (int i = 0; i < macAddress.length; i++) {

                if (i != 0) {
                    buffer.append(':');
                }

                String str = Integer.toHexString(macAddress[i] & 0xff);

                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddress = buffer.toString().toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strMacAddress;
    }

    public static WifiInfoEntity getWifiInfo() {

        try {

            Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
            while (eni.hasMoreElements()) {
                NetworkInterface networkCard = eni.nextElement();

                if (!networkCard.isUp()) {
                    continue;
                }
                String DisplayName = networkCard.getDisplayName();
                List<InterfaceAddress> addressList = networkCard.getInterfaceAddresses();
                for (InterfaceAddress interfaceAddress : addressList) {
                    InetAddress address = interfaceAddress.getAddress();

                    if (!address.isLoopbackAddress()) {
                        String hostAddress = address.getHostAddress();
                        if (!(hostAddress.indexOf(":") > 0)) {
                            String maskAddress = calcMaskByPrefixLength(interfaceAddress.getNetworkPrefixLength());

                            return new WifiInfoEntity(hostAddress, maskAddress);
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String calcMaskByPrefixLength(int length) {

        int mask = 0xffffffff << (32 - length);
        int partsNum = 4;
        int bitsOfPart = 8;
        int[] maskParts = new int[partsNum];
        int selector = 0x000000ff;

        for (int i = 0; i < maskParts.length; i++) {
            int pos = maskParts.length - 1 - i;
            maskParts[pos] = (mask >> (i * bitsOfPart)) & selector;
        }

        String result = "";
        result = result + maskParts[0];
        for (int i = 1; i < maskParts.length; i++) {
            result = result + "." + maskParts[i];
        }
        return result;
    }

    private static String calcSubnetAddress(String ip, String mask) {
        String result = "";
        try {
            // calc sub-net IP
            InetAddress ipAddress = InetAddress.getByName(ip);
            InetAddress maskAddress = InetAddress.getByName(mask);

            byte[] ipRaw = ipAddress.getAddress();
            byte[] maskRaw = maskAddress.getAddress();

            int unsignedByteFilter = 0x000000ff;
            int[] resultRaw = new int[ipRaw.length];
            for (int i = 0; i < resultRaw.length; i++) {
                resultRaw[i] = (ipRaw[i] & maskRaw[i] & unsignedByteFilter);
            }

            // make result string
            result = result + resultRaw[0];
            for (int i = 1; i < resultRaw.length; i++) {
                result = result + "." + resultRaw[i];
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String meminfo() {
        String[] cmds = new String[]{"cat proc/meminfo"};
        ShellUtils.CommandResult rs = ShellUtils.execCommand(cmds, false, true);
        if (!TextUtils.isEmpty(rs.successMsg)) {
            String[] tmpList = rs.successMsg.split("kB");
            Double total = null, free = null, available = null, cached = null;
            for (String line : tmpList) {
                if (line.contains("MemTotal:")) {
                    total = Double.valueOf(Pattern.compile("[^0-9]").matcher(line).replaceAll(""));
                }
                if (line.contains("MemFree:")) {
                    free = Double.valueOf(Pattern.compile("[^0-9]").matcher(line).replaceAll(""));
                }

                if (line.contains("MemAvailable:")) {
                    available = Double.valueOf(Pattern.compile("[^0-9]").matcher(line).replaceAll(""));
                }

                if (line.contains("Cached:")) {
                    cached = Double.valueOf(Pattern.compile("[^0-9]").matcher(line).replaceAll(""));
                    if (total != null && total > 0 && free != null && free > 0) {
                        break;
                    }
                }
            }
            available = 0.00;
            return String.valueOf(100-Math.round((free + cached) / total * 100)) + "%";
            //Log.e("debug","DDR使用率："+String.valueOf((total-free-available)/total*100)+"%");
        } else {
            return "unknown";
        }
    }



}
